/*
 * Copyright (c) 2018-2999 北京小象智慧信息科技有限公司 All rights reserved.
 *
 * https://www.xiaoxiangai.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.api.listener;

import com.google.common.collect.Lists;
import com.yami.shop.bean.app.dto.*;
import com.yami.shop.bean.app.param.OrderParam;
import com.yami.shop.bean.event.ConfirmOrderEvent;
import com.yami.shop.bean.event.ShopCartEvent;
import com.yami.shop.bean.model.*;
import com.yami.shop.bean.order.ConfirmOrderOrder;
import com.yami.shop.bean.order.ShopCartEventOrder;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.Arith;
import com.yami.shop.security.util.SecurityUtils;
import com.yami.shop.service.*;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 确认订单信息时的默认操作
 * @author LGH
 */
@Component("defaultConfirmOrderListener")
@AllArgsConstructor
public class ConfirmOrderListener {

    private final UserAddrService userAddrService;

    private final TransportManagerService transportManagerService;

    private final ProductService productService;

    private final SkuService skuService;

    private final ShopDetailService shopDetailService;

    private final ActivityService activityService;

    /**
     * 计算订单金额
     */
    @EventListener(ConfirmOrderEvent.class)
    @Order(ConfirmOrderOrder.DEFAULT)
    public void defaultConfirmOrderEvent(ConfirmOrderEvent event) {

        ShopCartOrderDto shopCartOrderDto = event.getShopCartOrderDto();
        //获得起送价格
        Long shopId = shopCartOrderDto.getShopId();
        ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(shopId);
        if(shopDetail!=null){
            Double startPrice = shopDetail.getStartPrice();
            shopCartOrderDto.setStartPrice(startPrice);
        }
        OrderParam orderParam = event.getOrderParam();

        String userId = SecurityUtils.getUser().getUserId();

        // 订单的地址信息
        UserAddr userAddr = userAddrService.getUserAddrByUserId(orderParam.getAddrId(), userId);

        double total = 0.0;

        int totalCount = 0;

        double transfee = 0.0;

        double actualTotal = 0.0;

        double orderReduce = 0.0;

        boolean isOnlySelfmentionflag = false;
        for (ShopCartItemDto shopCartItem : event.getShopCartItems()) {
            // 获取商品信息
            Product product = productService.getProductByProdId(shopCartItem.getProdId());
            //查看商品是否仅支持自提
            String isOnlySelfmention =  product.getIsOnlySelfmention();
            if("0".equals(isOnlySelfmention)){
                isOnlySelfmentionflag = true;
            }
            // 获取sku信息
            Sku sku = skuService.getSkuBySkuId(shopCartItem.getSkuId());
            if (product == null || sku == null) {
                shopCartOrderDto.setErrorMessage("购物车包含无法识别的商品");
            }
            if (product.getStatus() != 1 || sku.getStatus() != 1) {
                shopCartOrderDto.setErrorMessage("商品[" + sku.getProdName() + "]已下架");
            }

            totalCount = shopCartItem.getProdCount() + totalCount;
            total = Arith.add(shopCartItem.getProductTotalAmount(), total);
            //查看当前商品是不是活动商品,查看活动价格是否有值
            Long activityId = product.getActivityId();
            Double activityPrice = product.getActivityPrice();
            Product activityProd = productService.getActivityProd(shopCartItem.getProdId());

            //判断当前的活动商品有没有超过活动最大购买数量
            ActivityPro activityPro = activityService.getActivityProdByProdId(shopCartItem.getProdId());
            //商品数量不能超过限购数量
            if(shopCartItem.getActivityTimesFlag()!=null) {
                if (shopCartItem.getActivityTimesFlag() == 1) {
                    //获取用户已购买的最大购买数量
                    Integer maxNumber = activityService.getMaxNumber(userId, shopCartItem.getProdId());
                    //用户剩余购买数量
                    int activityTimes = activityPro.getActivityTimes();
                    if (maxNumber == null) {
                        maxNumber = 0;
                    }
                    int maxbuyNumber = activityTimes - maxNumber;
                    if (maxbuyNumber < shopCartItem.getProdCount()) {
                        shopCartOrderDto.setErrorMessage("购物车中活动商品超过最大购买数量");
                    }
                }
            }

            if(activityId>0){
                if(activityProd!=null) {
                    actualTotal = Arith.add(shopCartItem.getFavorablePrice(),actualTotal);
                }else{
                    if (new BigDecimal(String.valueOf(activityPrice)).compareTo(new BigDecimal("0")) > 0) {
                        //活动商品总价格
                        activityPrice = Arith.sub(activityPrice,shopCartItem.getDiscountMoney());
                        Double totalPrice = Arith.mul(activityPrice, shopCartItem.getProdCount());
                        actualTotal = Arith.add(totalPrice, actualTotal);

                    } else {
                        actualTotal = Arith.add(shopCartItem.getFavorablePrice(), actualTotal);
                    }
                }

            }else{
                actualTotal = Arith.add(shopCartItem.getFavorablePrice(),actualTotal);
            }


            Double discountMoney = shopCartItem.getDiscountMoney();
            if(discountMoney == null){
                discountMoney = Double.valueOf(0);
            }
            orderReduce = Arith.add(orderReduce,discountMoney);
            // 用户地址如果为空，则表示该用户从未设置过任何地址相关信息
            if (userAddr != null) {
                // 每个产品的运费相加
//                transfee = Arith.add(transfee, transportManagerService.calculateTransfee(shopCartItem, userAddr));
            }

            shopCartItem.setActualTotal(actualTotal);
            shopCartOrderDto.setActualTotal(Arith.add(actualTotal, transfee));
            shopCartOrderDto.setTotal(total);
            shopCartOrderDto.setTotalCount(totalCount);
            shopCartOrderDto.setTransfee(transfee);
            shopCartOrderDto.setShopReduce(orderReduce);
            shopCartOrderDto.setOnlySelfmention(isOnlySelfmentionflag);
        }
    }
}
